package com.example.easypoi.controller;


import com.example.easypoi.entity.User;
import com.example.easypoi.entity.UserIn;
import com.example.easypoi.service.UserReportService;
import com.example.easypoi.util.FileUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.jeecgframework.poi.excel.entity.result.ExcelImportResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@RestController
@RequestMapping("/api/user-report")
public class UserReportController {

    @Autowired
    private UserReportService userReportService;

    /**
     * 1. 导出用户订单报表（多级结构 + 图片 + 样式）
     */
    @GetMapping("/export")
    public void exportUserReport(HttpServletResponse response) throws IOException {
        List<User> list = userReportService.buildMockData();

        ExportParams params = new ExportParams("用户订单报表", "用户数据", ExcelType.XSSF);
        params.setStyle(UserExportStyler.class); // 自定义样式类
        Workbook workbook = ExcelExportUtil.exportExcel(params, User.class, list);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=user_report.xlsx");
        workbook.write(response.getOutputStream());
    }
    @GetMapping("/template2")
    public ResponseEntity<Resource> downloadTemplate2() throws MalformedURLException {
        Path path = Paths.get("src/main/resources/template/user_import_template.xlsx");
        Resource resource = new UrlResource(path.toUri());
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=user_template.xlsx")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }
    /**
     * 2. 下载导入模板
     */
    @GetMapping("/template")
    public ResponseEntity<Resource> downloadTemplate() throws IOException {
        // 1. 从 classpath 读取模板
        ClassPathResource resource = new ClassPathResource("templates/user_import_template.xlsx");

        // 2. 判断资源是否存在
        if (!resource.exists()) {
            return ResponseEntity.notFound().build();
        }

        // 3. 返回下载响应
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename*=UTF-8''user_template.xlsx") // 支持中文名
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .contentLength(resource.contentLength())          // 可选：带上长度
                .body(resource);
    }

    /**
     * 3. 上传并导入用户数据（含校验）
     */
    @PostMapping("/import")
    public String importUser(@RequestParam("file") MultipartFile file) throws Exception {
        ImportParams params = new ImportParams();
        params.setTitleRows(1); // 标题行
        params.setHeadRows(1);  // 表头行

        List<User> list = ExcelImportUtil.importExcel(file.getInputStream(), UserIn.class, params);

        return "成功导入 " + list.size() + " 条数据";
    }
}